package com.example.myapplication.listener;

import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

public class TabListener<T extends Fragment> implements ActionBar.TabListener  {
    private final AppCompatActivity mActivity;
	private final String mTag;
	private final Class<T> mClass;
    private final Bundle mArgs;
	private Fragment mFragment;
    public TabListener(AppCompatActivity activity, String tag, Class<T> clz) {
        this(activity, tag, clz, null);
    }

    public TabListener(AppCompatActivity activity, String tag, Class<T> clz, Bundle args) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
        mArgs = args;

        mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
        if (mFragment != null && !mFragment.isDetached()) {
            /*
            FragmentTransaction是封装了Fragment变换所要用的函数，
            包括将Fragment加入到Activity的add()函数，
            将Fragment从当前界面分离的Detach()函数，
            将被Detach()函数分离的Fragment重新连接到界面的attach()函数
             */
            FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
            ft.detach(mFragment);
            ft.commit();
        }
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, androidx.fragment.app.FragmentTransaction ft) {
        if (mFragment == null) {
            mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            ft.attach(mFragment);
        }
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, androidx.fragment.app.FragmentTransaction ft) {
        if (mFragment != null) {
            ft.detach(mFragment);
        }
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, androidx.fragment.app.FragmentTransaction ft) {
        Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show();
    }
}
